<template>
  <div class="bar-chart">
    <div ref="chart" :style="{ width: '100%', height: '400px' }"></div>
  </div>
</template>

<script>
import {charts} from "@/api/charts/charts";
import * as echarts from 'echarts';

export default {
  name: 'BarChart',
  components: {},
  props: [],
  data() {
    return {
      chartInstance: null,
      yAxisData: [],
      seriesData: []
    };
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {
    this.initChart();
    this.fetchData();
  },
  methods: {
    initChart() {
      this.chartInstance = echarts.init(this.$refs.chart);
      this.setOptions();
    },
    setOptions() {
      this.chartInstance.setOption({
        title: {
          text: '供应商订单排行',
          left: 'center'
        },
        tooltip: {},
        xAxis: {
          type: 'category',
          data: this.yAxisData
        },
        yAxis: {
          type: 'value'
        },
        series: [{
          data: this.seriesData,
          type: 'bar'
        }]
      });
    },

    async fetchData() {
      try {
        const response = await charts(); // 假设这是您的请求函数
        const data = response.data;

        // 检查数据是否为数组
        if (Array.isArray(data)) {
          this.yAxisData = data.map(item => item.vendorName);
          this.seriesData = data.map(item => item.orderCount);

          // 使用 Vue 的 nextTick 确保 DOM 更新后再更新图表
          this.$nextTick(() => {
            this.setOptions();
          });
        } else {
          console.error('Received data is not an array:', data);

          // 如果数据不是数组，尝试处理成数组
          if (typeof data === 'object' && data !== null) {
            // 假设 data 是一个对象，且具有 vendorName 和 orderCount 属性
            this.yAxisData = [data.vendorName];
            this.seriesData = [data.orderCount];

            // 使用 Vue 的 nextTick 确保 DOM 更新后再更新图表
            this.$nextTick(() => {
              this.setOptions();
            });
          } else {
            // 如果数据既不是数组也不是对象，则设置为空数组
            this.yAxisData = [];
            this.seriesData = [];

            // 使用 Vue 的 nextTick 确保 DOM 更新后再更新图表
            this.$nextTick(() => {
              this.setOptions();
            });
          }
        }
      } catch (error) {
        console.error('Error fetching data:', error);
      }
    },
  }
};
</script>

<style scoped>
.bar-chart {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}

.bar-chart .el-card__body {
  padding: 20px;
}
</style>
